<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<c:set var="basePath" value="${pageContext.request.contextPath}"/>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>用户列表</title>
	<link href="${basePath }/static/plugins/layui/css/layui.css" rel="stylesheet"/>
	<link href="${basePath}/static/build/css/app.css" rel="stylesheet" media="all">
	<style>
		#roleModal{
			display: none;
			text-align: center;
			padding: 4px 0 16px 0;
		}
		#roleModal .layui-form-checkbox{
			margin: 12px 0 0 0;
		}
	</style>
</head>
<body>
<div class="" id="user-main" style="margin: 12px;">
	<div class="layui-row">
		<div class="layui-col-xs8">
			<div class="layui-btn-group " id="toolbar">
				<button title="删除" class="layui-btn layui-btn-primary" data-type="deleteBatch"><i class="layui-icon">&#xe640;</i></button>
				<button title="刷新" class="layui-btn layui-btn-primary" data-type="refresh"><i class="layui-icon">&#x1002;</i></button>
				<button title="新增" class="layui-btn layui-btn-primary" data-type="toInsert"><i class="layui-icon">&#xe61f;</i></button>
			</div>
		</div>
		<div class="layui-col-xs4">
			<div id="search-inputs"></div>
		</div>
	</div>
	<div id="table" lay-filter="user-table"></div>
</div>
<div id="roleModal">
	<form class="layui-form" action="javascript:;">
		<input name="userId" hidden>
		<c:forEach items="${roles}" var="r">
			<input type="checkbox" lay-filter="role" name="roleId" title="${r.roleName}" value="${r.roleId}">
		</c:forEach>
	</form>
</div>

<script src="${basePath }/static/plugins/layui/layui.js"></script>
<script src="${basePath }/static/plugins/jq/jquery-2.2.4.min.js"></script>
<script src="${basePath }/static/build/js/common.js"></script>
<script>
    layui.use(['form', 'table', 'layer', 'element', 'search'], function() {
        var form = layui.form,
            table = layui.table,
            layer = layui.layer,
            search = layui.search;


        var tableIns = table.render({
            elem: '#user-main #table'
            ,height: 'full'
			,id: 'idTable'
            ,url: '${basePath}/admin/user/query' //数据接口
            ,page: true //开启分页
            ,limit: 10
            ,cols: [[ //表头
                {type: 'checkbox', width: 50}
                ,{field: 'userId', title: 'ID', sort: true}
                ,{field: 'username', title: '用户名', edit: 'text'}
                ,{field: 'nickname', title: '昵称',  sort: true, edit: 'text'}
                ,{field: 'email', title: '邮箱', edit: 'text' }
                ,{field: 'ctime', title: '注册时间',
					templet: function (item) {
						return getDateFromMill(item.ctime);
                    }
				}
                ,{field: 'avatar', title: '头像',align:'center',
					templet: function (item) {
                    	var img = '<img src="${basePath}'+ item.avatar +'" class="layui-nav-img">';
						return img;
                    }
				}
                ,{field: 'locked', title: '锁定',align:'center',
					templet: function (item) {
						var $switch = $('<input>').attr({
                            'type': 'checkbox',
                            'name': 'lock',
                            'lay-filter': 'lock',
                            'lay-skin': 'switch',
							'lay-text': 'ON|OFF',
							'data-id': item.userId
						});
						if (item.locked == 0){
                            $switch.attr('checked', 'checked')
						}
						return $switch[0].outerHTML;
                    }
				}
                ,{fixed: 'right', align:'center', toolbar: '#commont-bar'}
            ]]
        });

        //初始化检索组件
        search.render({
            tableIns: tableIns,  //表格对象，必须
            elem: '#search-inputs',  //搜索的div的id或class，必须
            searchName: 'param',  //模糊查询文本框的name
            placeholder: '模糊查询',
            more: true,  //是否需要更多筛选，可选，默认为true，true/false
            fields: [  //更多筛选中的选项，目前仅支持文本框，其余需layui渲染的组件尚未测试，可选
                {name: 'email', type: 'text', title: '邮箱', placeholder: '请输入邮箱'}  //name：input的name，type：input的type，title：显示的名称，placeholder：input的提示文字
                ,{name: 'username', type: 'text', title: '用户名', placeholder: '请输入用户名'}
                ,{name: 'nickname', type: 'text', title: '昵称', placeholder: '请输入昵称'}
                ,{name: 'locked', type: 'checkbox', title: '锁定', placeholder: '是否锁定'}
            ]
        });

        //监听单元格编辑
        table.on('edit(user-table)', function(obj){
            var value = obj.value //得到修改后的值
                ,data = obj.data //得到所在行所有键值
                ,field = obj.field; //得到字段
            var reqData = {};
            reqData[field] = value;
            reqData['userId'] = data.userId;
            action.update(reqData);
        });

        //锁定状态切换
        form.on('switch(lock)', function(data){
            var locked = 1;
            //on
            if(data.elem.checked){
                locked = 0;
			}
            var reqData = {};
            reqData['locked'] = locked;
            reqData['userId'] = $(data.elem).attr('data-id');
            console.log(reqData);
            action.update(reqData);
        });

        //切换角色
        form.on('checkbox(role)', function(data){
            var userId = $('input[name="userId"]').val(),
				checked = data.elem.checked,
				method = undefined;
            //insert
            if (checked) {
                method = 'insert';
			}
			//delete
			else {
                method = 'delete'
			}
			$.ajax({
				url: '${basePath}/power/userRole/' + method,
				type: 'post',
				data: {
				    userId: userId,
					roleId: $(data.elem).attr('value')
                },
				dataType: 'json',
				success: function (res) {
                    layer.msg(res.msg);
                },
				error: function (xhr) {
					console.log(xhr)
                }
			})

        });

        table.on('tool(user-table)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）

            if(layEvent === 'role'){ //检查角色
				$.ajax({
					url: '${basePath}/power/userRole/getRoleByUserId',
					type: 'post',
					dataType: 'json',
					data: {
					    userId: data.userId
                    },
					success: function (res) {
                        $('input[name="roleId"]').removeAttr('checked');
                        $('input[name="userId"]').val(data.userId);
                        form.render('checkbox');
						if (res.code == 200){
						    var list = res.object;
						    for (var i = 0; i < list.length; i++){
						        var item = list[i];
						        var roleId = item.roleId;
						        $('input[name="roleId"]').each(function (index, elem) {
									var tmpId = $(elem).val();
									if (tmpId == roleId){
									    $(elem).prop('checked', true);
									    $(elem).next().addClass('layui-form-checked');
									}
                                });
                            }
                        }

                        layer.open({
                            title: '切换角色',
                            type: 1,
                            content: $('#roleModal'),
                            shade: false,
                            shadeClose: true
                        })
                    }
				});



            } else if(layEvent === 'del'){ //删除
                layer.confirm('是否确认删除', function(index){
                    obj.del();
                    var id = [data.userId];
                    action.delete(id);
                    layer.close(index);
                });
            }
        });

        var action = {
            deleteBatch: function(){ //批量删除
                var checkStatus = table.checkStatus('idTable')
                    ,data = checkStatus.data;
                if(data.length == 0){
                    return;
                }
                var ids = [];
                for(var i = 0; i < data.length; i++ ){
                    ids.push(data[i].userId);
                }

                action.delete(ids);
                tableIns.reload();
            },
            refresh: function(){
                tableIns.reload();
            },
            toInsert: function(){
                var options = {
                    url: "${basePath }/admin/user/toinsert",
                    icon: "&#xe658;",
                    title: "新增用户",
                    id: "user-insert"
                }
                parent.tab.tabAdd(options);
            },
            delete: function(ids){
                $.ajax({
                    url: '${basePath}/admin/user/delete',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        id: ids
                    },
                    success: function(resp){
                        if(resp.code==10000){
                            layer.msg('删除成功',{
                                time: 1000
                            }, function(){
                                //tableIns.reload();
                            })
                        }
                    }
                })
            },
            update: function(reqData){
                $.ajax({
                    url: '${basePath}/admin/user/update',
                    type: 'post',
                    dataType: 'json',
                    data:reqData,
                    success: function(resp){
                        console.log(resp)
                        if(resp.code==10000){
                            layer.msg('更新成功',{
                                time: 1000
                            });
                        }
                    }
                })
            }
        };

        $('#user-main #toolbar .layui-btn').on('click', function(){
            var type = $(this).data('type');
            action[type] ? action[type].call(this) : '';
        });

        action.refresh();
    });


</script>
<script type="text/html" id="commont-bar">
	<a class="layui-btn layui-bg-blue layui-btn-xs" lay-event="role">切换角色</a>
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
</body>
</html>